package cn.hp.shiro;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

//用户认证（登录）
public class TestApp {

	public static void main(String[] args) {
		String username = "zhangsan";
		String password = "123456";
		
		//1  创建SercurityManager工厂
		Factory<SecurityManager>factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		//2  从工厂中获取SecurityManager
		SecurityManager securityManager = factory.getInstance();
		//3  把当前的SecurityManager绑定到当前线程中
		SecurityUtils.setSecurityManager(securityManager);
		//4  获取Subject主体
		Subject subject = SecurityUtils.getSubject();
		//5  封装用户名和密码
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		//6  进行登录认证
		try {
			subject.login(token);
			System.out.println("是否认证成功："+subject.isAuthenticated());
		} catch (AuthenticationException e) {
			System.out.println("用户名或密码错误！");
		}
		
		System.out.println("--------------------");
		
		//判断用户是否有某个角色
		boolean hasRole = subject.hasRole("role1");
		System.out.println(hasRole);
		
		//分别判断用户是否具有集合里面的角色
		List<String> roleIdentifiers = new ArrayList<>();
		roleIdentifiers.add("role1");
		roleIdentifiers.add("role2");
		roleIdentifiers.add("role3");
		boolean[] hasRoles = subject.hasRoles(roleIdentifiers);
		System.out.println(Arrays.toString(hasRoles));
		
		//判断用户是否同时具有集合里面的角色
		boolean hasAllRoles = subject.hasAllRoles(roleIdentifiers);
		System.out.println(hasAllRoles);
		
		System.out.println("--------------------------");
		
		//判断用户是否用户某个权限
		boolean permitted = subject.isPermitted("user:query");
		System.out.println(permitted);
		
		//分别判断用户是否具有集合里面的权限
		String[] permissions = {"user:query","user:add","user:update"};
		boolean[] permitted2 = subject.isPermitted(permissions);
		System.out.println(Arrays.toString(permitted2));
		
		//判断用户是否同时具有集合里面的权限
		boolean permittedAll = subject.isPermittedAll(permissions);
		System.out.println(permittedAll);
		
		
	}
}
